package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-sys-mgr/cache"
	"novel-sys-mgr/model"
	"strconv"
	"time"
)

func CreateNovel(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	if title == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := model.Novel{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func ListNovel(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var list []model.Novel
	redis_key := "list_" + strconv.Itoa(page)
	CacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&list)
		jsData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(CacheData), &list)
	}

	var count int64
	model.DB.Model(&model.Novel{}).Count(&count)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": gin.H{
			"count": count,
			"list":  list,
		},
	})
	return
}

func NovelInfo(c *gin.Context) {
	id := c.Query("id")
	var list model.Novel
	redis_key := "info_" + id
	CacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CacheData == "" {
		model.DB.Where("id=?", id).Find(&list)
		jsData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(CacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取详情成功",
		"data": list,
	})
	return
}

func DelNovel(c *gin.Context) {
	id := c.Query("id")
	var novel model.Novel
	err := model.DB.Where("id=?", id).Delete(&novel).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
